package de.baumann.browser.views.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import de.baumann.browser.R
import de.baumann.browser.js.VaptchaInterface
import kotlinx.android.synthetic.main.dialog_vaptcha.*

class VaptchaDialog(context: Context,var callback: Callback) : BaseDialog(context) {
    override fun laoutId(): Int {
        return R.layout.dialog_vaptcha
    }

    override fun initView() {
        setVaptcha()
        vaptchaWeb.loadUrl("https://v.vaptcha.com/app/android.html?vid=5f0e614a8d41fe366eb1e685&scene=0&lang=zh-CN");
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun setVaptcha() {
        vaptchaWeb.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null)
        vaptchaWeb.settings.useWideViewPort = true
        vaptchaWeb.settings.loadWithOverviewMode = true
        vaptchaWeb.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        vaptchaWeb.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view!!.loadUrl(url)
                return true
            }
        }
        vaptchaWeb.settings.javaScriptEnabled = true;
        vaptchaWeb.addJavascriptInterface(VaptchaInterface(object :VaptchaInterface.VaptchaCallback{
            override fun pass(token: String) {
                dismiss()
                callback.callback(token)
            }

            override fun cancel() {
                dismiss()
            }

        }), "vaptchaInterface")
    }
}

interface Callback{
    fun callback(token:String)
}